package com.ryoma.thread;


import com.ryoma.Utils.*;
import com.ryoma.model.Log;
import com.ryoma.model.Url;
import com.ryoma.model.elevator.ElevatorRealTimeDatas;
import com.ryoma.model.environment.EnvironmentRealTimeDatas;
import com.ryoma.model.gps.GpsInfos;
import com.ryoma.model.towercrane.TowerRealTimeDatas;
import net.sf.json.JSONArray;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionUtils;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DBdataBuildThread implements Runnable {

    private volatile boolean flag = true;

    private volatile long index;

    private Url url;

    private List list;

    public DBdataBuildThread(Url url){
        this.url = url;
    }

    @Override
    public void run() {
        while (flag){
            StringBuffer paramsResult = new StringBuffer();
            Map<String,String> postMap = new ConcurrentHashMap<String, String>();
            if(url.getCode().equals("TowerRealTimeDatas")){
                TowerRealTimeDatas towerRealTimeDatas = new TowerRealTimeDatas();
                if(Consts.idIndexParam.get("TowerRealTimeDatas")!=null){
                    towerRealTimeDatas.setId(Long.parseLong(Consts.idIndexParam.get("TowerRealTimeDatas").toString()));
                }
                paramsResult.append(buildDBdatasRequestMsg(url,list));
            } else if (url.getCode().equals("ElevatorRealTimeDatas")){
                ElevatorRealTimeDatas elevatorRealTimeDatas = new ElevatorRealTimeDatas();
                if(Consts.idIndexParam.get("ElevatorRealTimeDatas")!=null){
                    elevatorRealTimeDatas.setId(Long.parseLong(Consts.idIndexParam.get("ElevatorRealTimeDatas").toString()));
                }
                paramsResult.append(buildDBdatasRequestMsg(url,list));
            } else if (url.getCode().equals("EnvironmentRealTimeDatas")){
                EnvironmentRealTimeDatas environmentRealTimeDatas = new EnvironmentRealTimeDatas();
                if(Consts.idIndexParam.get("EnvironmentRealTimeDatas")!=null){
                    environmentRealTimeDatas.setId(Long.parseLong(Consts.idIndexParam.get("ElevatorRealTimeDatas").toString()));
                }
                paramsResult.append(buildDBdatasRequestMsg(url,list));
            } else if (url.getCode().equals("GpsInfos")){
                GpsInfos gpsInfos = new GpsInfos();
                if(Consts.idIndexParam.get("GpsInfos")!=null){
                    gpsInfos.setId(Long.parseLong(Consts.idIndexParam.get("ElevatorRealTimeDatas").toString()));
                }
                paramsResult.append(buildDBdatasRequestMsg(url,list));
            }

            Log log = new Log();
            log.setType(url.getId());
            try {
                if (url.getEndPoint().getType() == Consts.EndPointType_POST) {
                    postMap.put("params", paramsResult.toString().trim());
                    log.setSendMsg(WebConnectorUtils.getHttpResult(url.getEndPoint().getUrl(), postMap));
                } else if (url.getEndPoint().getType() == Consts.EndPointType_WebService) {
                    log.setSendMsg(WebServicesRpcUtils.rpcwebservice(url.getEndPoint().getUrl(), url.getEndPoint().getNameSpace(), url.getEndPoint().getFunctionName(), new Object[]{paramsResult}));
                }
                CommonUtils.insertIntoLog(log);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(300000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private String buildDBdatasRequestMsg(Url url, List list){
        StringBuffer sb_params = new StringBuffer();
        JSONArray jsonArray = new JSONArray();
        Map<String,Object> resultMap = new HashMap<String, Object>();
        for(String responseField:url.getResponseField().split(",")) {//获取需要传输的列信息
            String[] fields = responseField.split("-");
            Map<String, Object> map = new HashMap<String, Object>();
            for(int i=0;i<list.size();i++){
                Object data = list.get(i);

                if(data.getClass() == TowerRealTimeDatas.class){
                    if(i == 0){
                        Consts.idIndexParam.put(url.getCode(),((TowerRealTimeDatas)data).getId());
                        index =((TowerRealTimeDatas)data).getId();
                    }
                    for(int j = 1;j<fields.length;j++){
                        String field = fields[j];
                        map.put(field,ReflectionUtils.invokeGetter((TowerRealTimeDatas)data,field));
                    }
                }else if(data.getClass() == ElevatorRealTimeDatas.class){
                    if(i == 0){
                        Consts.idIndexParam.put(url.getCode(),((ElevatorRealTimeDatas)data).getId());
                        index =((ElevatorRealTimeDatas)data).getId();
                    }
                    for(int j = 1;j<fields.length;j++){
                        String field = fields[j];
                        map.put(field,ReflectionUtils.invokeGetter((ElevatorRealTimeDatas)data,field));
                    }
                }else if(data.getClass() == EnvironmentRealTimeDatas.class){
                    if(i == 0) {
                        Consts.idIndexParam.put(url.getCode(),((EnvironmentRealTimeDatas)data).getId());
                        index =((EnvironmentRealTimeDatas)data).getId();
                    }
                    for(int j = 1;j<fields.length;j++){
                        String field = fields[j];
                        map.put(field,ReflectionUtils.invokeGetter((EnvironmentRealTimeDatas)data,field));
                    }
                }else if(data.getClass() == GpsInfos.class){
                    if(i == 0) {
                        Consts.idIndexParam.put(url.getCode(),((GpsInfos)data).getId());
                        index =((GpsInfos)data).getId();
                    }
                    for(int j = 1;j<fields.length;j++){
                        String field = fields[j];
                        map.put(field,ReflectionUtils.invokeGetter((GpsInfos)data,field));
                    }
                }
                jsonArray.add(JsonUtils.paramsToJson(map));
            }
        }
        resultMap.put("result",jsonArray.toString());
        System.out.println(new Date()+"============="+url.getCode()+" build Finish ============");
        return JsonUtils.paramsToJson(resultMap).toString();
    }
}
